package com.unittec.drainage.provider.service;

import com.unittec.drainage.provider.ApplicationContextProvider;
import com.unittec.drainage.provider.log.Log;
import lombok.Data;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @description: WebSocket服务端
 * @author: wuxinwei
 * @create: 2019年12月10日18:18:12
 **/
@ServerEndpoint(value = "/websocket/{userName}")
@Component
@Data
public class WebSocketServer {

    /**
     * concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
     */
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<>();

    /**
     * 与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
    private Session session;

    /**
     * 接收当前用户
     */
    private String userName = "";

    /**
     * 接收当前用户
     */
    private String userId = "";

    /**
     * token
     */
    private String token = "";

    /**
     * 消息业务类型
     */
    private String planType = "";

    private String appId = "";

    private String appKey = "";

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userName") String userName) {
        this.session = session;
        Map<String, List<String>> paramMap = session.getRequestParameterMap();
        if (paramMap != null) {
            this.token = paramMap.get("token") != null ? paramMap.get("token").get(0) : "";
            this.userName = paramMap.get("userName") != null ? paramMap.get("userName").get(0) : "";
            this.userId = paramMap.get("userId") != null ? paramMap.get("userId").get(0) : "";
            this.planType = paramMap.get("planType") != null ? paramMap.get("planType").get(0) : "";
            this.appId = paramMap.get("appId") != null ? paramMap.get("appId").get(0) : "";
            this.appKey = paramMap.get("appKey") != null ? paramMap.get("appKey").get(0) : "";
        }
        webSocketSet.add(this);
        ApplicationContextProvider.getBean(RootCommonUtils.class).sendWebSocketMsg(this.userId, this.token, this.appId, this.appKey, "BUSINESS");
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);
    }

    /**
     * 给指定联系人发送消息
     *
     * @param userName
     * @param message
     * @throws IOException
     */
    public static void sendMessageByUserName(String userName, String message) throws IOException {
        if (StringUtils.isBlank(userName)) {
            return;
        }
        for (WebSocketServer item : webSocketSet) {
            if (userName.equalsIgnoreCase(item.userName)) {
                item.session.getBasicRemote().sendText(message);
            }
        }
    }

    /**
     * 给指定联系人发送消息
     *
     * @param userId
     * @param message
     * @throws IOException
     */
    public static void sendMessageByUserId(String userId, String message) throws IOException {
        if (StringUtils.isBlank(userId)) {
            return;
        }
        for (WebSocketServer item : webSocketSet) {
            if (userId.equalsIgnoreCase(item.userId)) {
                item.session.getBasicRemote().sendText(message);
            }
        }
    }

    /**
     * 给所有人发送未读消息
     *
     * @throws IOException
     */
    public static void sendMessageByAll() throws IOException {
        for (WebSocketServer item : webSocketSet) {
            ApplicationContextProvider.getBean(RootCommonUtils.class).sendWebSocketMsg(item.userId, item.token, item.appId, item.appKey, "BUSINESS");
        }
    }

    /**
     * 根据token发送消息
     *
     * @param token
     * @param message
     */
    public static void sendMessageByToken(String token, String message) throws IOException {
        if (StringUtils.isBlank(token)) {
            return;
        }
        for (WebSocketServer item : webSocketSet) {
            if (token.equalsIgnoreCase(item.token)) {
                item.session.getBasicRemote().sendText(message);
            }
        }
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        session.getBasicRemote().sendText(message);
    }

    /**
     * 消息推送异常
     *
     * @param error
     */
    @OnError
    public void onError(Throwable error) {
        Log log = ApplicationContextProvider.getBean(Log.class);
        log.sysErrLog("webSocket onError", "发生错误", error);
    }

    /**
     * 实现服务器主动推送
     *
     * @param message
     */
    public void sendMessage(String message) {
        Log log = ApplicationContextProvider.getBean(Log.class);
        try {
            this.session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            log.sysErrLog("webSocket sendMessage", "用户名：" + this.userName + "消息发送失败，消息内容：" + message, e);
        }
    }

}